import { Button as AButton, Space as ASpace } from '@arco-design/web-vue'
import '@arco-design/web-vue/es/button/style/css.js'
import '@arco-design/web-vue/es/space/style/css.js'
import { defineComponent, h, ref, type Ref } from 'vue'

export interface CreateFooterOptions {
  onSubmit: (subType: 0 | 1) => void
  onCancel?: () => void
  loading?: Ref<boolean>
  showSaveBtn?: boolean
  class?: string
  style?: object
  submitText?: string
  cancelText?: string
  saveText?: string
}


export function useFooter(type: 'drawer' | 'modal') {
  const createFooter = (options: CreateFooterOptions) => {
    return defineComponent({
      render() {
        return h(CustomFooter, {
          type,
          onSubmit: options.onSubmit,
          onCancel: options.onCancel,
          loading: options.loading?.value,
          showSaveBtn: options.showSaveBtn,
          class: options.class,
          style: options.style,
          submitText: options.submitText,
          cancelText: options.cancelText,
          saveText: options.saveText
        })
      }
    })
  }

  return {
    createFooter
  }
}

export const CustomFooter = defineComponent({
  props: {
    type: {
      type: String,
      default: 'drawer'
    },
    showSaveBtn: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    submitText: {
      type: String,
      default: '提交'
    },
    cancelText: {
      type: String,
      default: '关闭窗口'
    },
    saveText: {
      type: String,
      default: '保存'
    }
  },
  emits: ['cancel', 'submit'],

  setup(_, ctx) {
    const handleCancel = () => {
      ctx.emit('cancel')
    }

    const handleSubmit = (type: 0 | 1) => {
      ctx.emit('submit', type)
    }

    const submit_loading = ref(false)

    return {
      handleCancel,
      handleSubmit,
      submit_loading
    }
  },
  render(props: {
    type: 'drawer' | 'modal'
    showSaveBtn: boolean
    saveText: string
    submitText: string
    cancelText: string
  }) {
    return props.type === 'drawer' ? (
      <ASpace>
        {props.showSaveBtn ? (
          <AButton type="outline" onClick={() => this.handleSubmit(0)}>
            {props.saveText}
          </AButton>
        ) : null}

        <AButton type="primary" loading={this.submit_loading} onClick={() => this.handleSubmit(1)}>
          {props.submitText}
        </AButton>

        <AButton
          type="outline"
          style="border: 1px solid #dddddd; color: #555555"
          onClick={this.handleCancel}
        >
          {props.cancelText}
        </AButton>
      </ASpace>
    ) : null
  }
})
